package com.interview.rtc.aigc.service.impl;

import com.interview.rtc.aigc.service.BiographicalNotesService;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;
import org.apache.poi.xwpf.extractor.XWPFWordExtractor;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
public class BiographicalNotesServiceImpl implements BiographicalNotesService {

    @Override
    public HashMap<String, Object> analyzeResumeNodes(MultipartFile file) {
        //判断文件是否为空
        if (file.isEmpty()) {
            throw new RuntimeException("文件为空");
        }
        //判断文件类型 是否为pdf/doc/docx
        if (!file.getContentType().equals("application/pdf")
         && !file.getContentType().equals("application/vnd.openxmlformats-officedocument.wordprocessingml.document")) {
            throw new RuntimeException("文件类型错误，只支持pdf/doc/docx");
        }

        //解析文件内容
        //1.提取pdf/doc/docx 中所有首字母大写的单词
        HashMap<String, Object> map = analyzeSkill(file);
        //2.提取pdf/doc/docx 中所有的项目经验的职责内容
        HashMap<String, Object> projectMap = analyzeProjectExperience(file);
        map.put("projects", projectMap);

        return map;
    }

    /**
     * 解析文件pdf/doc/docx 内容，提取技能点信息
     * @param file 上传的简历文件
     * @return 包含分类技能点信息的HashMap
     */
    public HashMap<String, Object> analyzeSkill(MultipartFile file) {
        try {
            // 提取文件内容
            String fileContent = extractFileContent(file);

            // 预定义技能词典和分类
            Map<String, Map<String, Double>> skillDictionary = initializeSkillDictionary();

            // 存储识别到的技能和可信度
            Map<String, Map<String, Double>> identifiedSkills = new HashMap<>();

            // 1. 使用预定义词典匹配
            for (Map.Entry<String, Map<String, Double>> category : skillDictionary.entrySet()) {
                Map<String, Double> foundSkills = new HashMap<>();
                for (Map.Entry<String, Double> skill : category.getValue().entrySet()) {
                    Pattern pattern = Pattern.compile("\\b" + Pattern.quote(skill.getKey()) + "\\b", Pattern.CASE_INSENSITIVE);
                    Matcher matcher = pattern.matcher(fileContent);
                    if (matcher.find()) {
                        foundSkills.put(skill.getKey(), skill.getValue());
                    }
                }
                if (!foundSkills.isEmpty()) {
                    identifiedSkills.put(category.getKey(), foundSkills);
                }
            }

            // 2. 动态识别首字母大写的潜在技术词汇
            Pattern capitalWordPattern = Pattern.compile("\\b[A-Z][a-zA-Z0-9]+\\b");
            Matcher capitalWordMatcher = capitalWordPattern.matcher(fileContent);
            Map<String, Double> unclassifiedSkills = new HashMap<>();

            while (capitalWordMatcher.find()) {
                String potentialSkill = capitalWordMatcher.group();
                boolean isAlreadyClassified = false;

                // 检查是否已在已分类技能中
                for (Map<String, Double> categorySkills : identifiedSkills.values()) {
                    if (categorySkills.containsKey(potentialSkill)) {
                        isAlreadyClassified = true;
                        break;
                    }
                }

                // 如果是新技能，添加到未分类技能中
                if (!isAlreadyClassified && potentialSkill.length() > 2) { // 过滤掉太短的词
                    unclassifiedSkills.put(potentialSkill, 0.5); // 设置默认可信度为0.5
                }
            }

            if (!unclassifiedSkills.isEmpty()) {
                identifiedSkills.put("unclassified", unclassifiedSkills);
            }

            // 将结果存储在HashMap中
            HashMap<String, Object> result = new HashMap<>();
            result.put("skills", identifiedSkills);
            return result;

        } catch (Exception e) {
            throw new RuntimeException("文件解析失败: " + e.getMessage());
        }
    }

    /**
     * 初始化技能词典，包含预定义的技能和对应的可信度分数
     * @return 技能词典
     */
    private Map<String, Map<String, Double>> initializeSkillDictionary() {
        Map<String, Map<String, Double>> skillDictionary = new HashMap<>();

        // 编程语言
        Map<String, Double> programmingLanguages = new HashMap<>();
        programmingLanguages.put("Java", 1.0);
        programmingLanguages.put("Python", 1.0);
        programmingLanguages.put("JavaScript", 1.0);
        programmingLanguages.put("TypeScript", 1.0);
        programmingLanguages.put("C++", 1.0);
        programmingLanguages.put("C#", 1.0);
        programmingLanguages.put("Go", 1.0);
        programmingLanguages.put("Ruby", 1.0);
        programmingLanguages.put("PHP", 1.0);
        programmingLanguages.put("Swift", 1.0);
        programmingLanguages.put("Kotlin", 1.0);
        skillDictionary.put("programming_languages", programmingLanguages);

        // 框架
        Map<String, Double> frameworks = new HashMap<>();
        frameworks.put("Spring", 1.0);
        frameworks.put("SpringBoot", 1.0);
        frameworks.put("SpringCloud", 1.0);
        frameworks.put("MyBatis", 1.0);
        frameworks.put("Hibernate", 1.0);
        frameworks.put("React", 1.0);
        frameworks.put("Vue", 1.0);
        frameworks.put("Angular", 1.0);
        frameworks.put("Django", 1.0);
        frameworks.put("Flask", 1.0);
        frameworks.put("Express", 1.0);
        frameworks.put("Laravel", 1.0);
        frameworks.put("ThinkPHP", 1.0);
        skillDictionary.put("frameworks", frameworks);

        // 数据库
        Map<String, Double> databases = new HashMap<>();
        databases.put("MySQL", 1.0);
        databases.put("PostgreSQL", 1.0);
        databases.put("MongoDB", 1.0);
        databases.put("Redis", 1.0);
        databases.put("Oracle", 1.0);
        databases.put("SQLServer", 1.0);
        databases.put("Cassandra", 1.0);
        skillDictionary.put("databases", databases);

        // 工具
        Map<String, Double> tools = new HashMap<>();
        tools.put("Git", 1.0);
        tools.put("Docker", 1.0);
        tools.put("Kubernetes", 1.0);
        tools.put("Jenkins", 1.0);
        tools.put("Maven", 1.0);
        tools.put("Gradle", 1.0);
        tools.put("IDEA", 1.0);
        tools.put("Docker", 1.0);
        tools.put("VSCode", 1.0);
        tools.put("Postman", 1.0);
        tools.put("Nginx", 1.0);
        skillDictionary.put("tools", tools);

        //工作流引擎
        Map<String, Double> workflowEngines = new HashMap<>();
        workflowEngines.put("Flowable", 1.0);
        workflowEngines.put("Camunda", 1.0);
        workflowEngines.put("Activiti", 1.0);

        //缓存技术
        Map<String, Double> cacheTechnologies = new HashMap<>();
        cacheTechnologies.put("Redis", 1.0);
        cacheTechnologies.put("Memcached", 1.0);
        cacheTechnologies.put("Ehcache", 1.0);

        //搜索引擎
        Map<String, Double> searchEngines = new HashMap<>();
        searchEngines.put("Elasticsearch", 1.0);
        searchEngines.put("Solr", 1.0);
        searchEngines.put("Lucene", 1.0);
        //消息队列
        Map<String, Double> messageQueues = new HashMap<>();
        messageQueues.put("RabbitMQ", 1.0);
        messageQueues.put("Kafka", 1.0);
        messageQueues.put("ActiveMQ", 1.0);
        messageQueues.put("RocketMq", 1.0);

        // 云服务
        Map<String, Double> cloudServices = new HashMap<>();
        cloudServices.put("AWS", 1.0);
        cloudServices.put("Azure", 1.0);
        cloudServices.put("GCP", 1.0);
        cloudServices.put("Alibaba", 1.0);
        cloudServices.put("Tencent", 1.0);
        cloudServices.put("Huawei", 1.0);
        cloudServices.put("CloudFlare", 1.0);
        cloudServices.put("Heroku", 1.0);
        skillDictionary.put("cloud_services", cloudServices);

        return skillDictionary;
    }

    /**
     * 解析文件内容，提取项目经验和职责信息
     * @param file 上传的简历文件
     * @return 包含项目经验和职责信息的HashMap
     *
     *
     * 提取的内容格式为：
                * {
            "total": 项目总数,
            "list": [
                {
                "name": "项目名称",
                "time": "项目时间",
                "responsibilities": ["职责1", "职责2", ...]
                },
    ...
  ]
}
     */
    private HashMap<String, Object> analyzeProjectExperience(MultipartFile file) {
        try {
            // 提取文件内容
            String fileContent = extractFileContent(file);

            // 存储项目经验信息
            HashMap<String, Object> projectsMap = new HashMap<>();
            ArrayList<Map<String, Object>> projectsList = new ArrayList<>();

            // 定义项目经验的正则表达式模式
            // 匹配项目名称（通常包含"项目"或"系统"关键词）
            Pattern projectPattern = Pattern.compile(
                "(?i)(?:项目名称[：:]\\s*)?([^\\n。]*(?:项目|系统|平台)[^\\n。]*)[\\n。]" +
                "(?:[^\\n]*(?:时间|日期)[：:]\\s*([^\\n。]+)[\\n。])?" +
                "(?:[\\s\\S]*?(?:职责|工作内容|主要工作|负责)[：:]\\s*([\\s\\S]*?)(?=(?:项目名称|\\d{4}[年/-]|$)))"
            );

            Matcher matcher = projectPattern.matcher(fileContent);

            while (matcher.find()) {
                Map<String, Object> projectInfo = new HashMap<>();
                String projectName = matcher.group(1);
                String projectTime = matcher.group(2);
                String responsibilities = matcher.group(3);

                // 清理和格式化提取的文本
                if (projectName != null) {
                    projectName = projectName.trim();
                }
                if (projectTime != null) {
                    projectTime = projectTime.trim();
                }
                if (responsibilities != null) {
                    // 将职责文本分割成列表
                    responsibilities = responsibilities.trim();
                    String[] respList = responsibilities.split("[\\n。；;]+");
                    ArrayList<String> formattedResp = new ArrayList<>();
                    for (String resp : respList) {
                        resp = resp.trim();
                        if (!resp.isEmpty()) {
                            formattedResp.add(resp);
                        }
                    }
                    projectInfo.put("responsibilities", formattedResp);
                }

                projectInfo.put("name", projectName);
                projectInfo.put("time", projectTime);

                projectsList.add(projectInfo);
            }

            // 按时间倒序排序（假设时间格式统一）
            projectsList.sort((p1, p2) -> {
                String time1 = (String) p1.get("time");
                String time2 = (String) p2.get("time");
                if (time1 == null || time2 == null) {
                    return 0;
                }
                return time2.compareTo(time1);
            });

            projectsMap.put("total", projectsList.size());
            projectsMap.put("list", projectsList);

            return projectsMap;

        } catch (Exception e) {
            throw new RuntimeException("解析项目经验失败: " + e.getMessage());
        }
    }

    /**
     * 从PDF或Word文档中提取文本内容
     * @param file 上传的文件
     * @return 提取的文本内容
     * @throws Exception 如果文件解析失败
     */
    @Override
    public String extractFileContent(MultipartFile file) throws Exception {
        String fileContent = "";
        if (file.getContentType().equals("application/pdf")) {
            // 处理PDF文件
            PDDocument document = PDDocument.load(file.getInputStream());
            PDFTextStripper stripper = new PDFTextStripper();
            fileContent = stripper.getText(document);
            document.close();
        } else {
            // 处理Word文档
            XWPFDocument document = new XWPFDocument(file.getInputStream());
            XWPFWordExtractor extractor = new XWPFWordExtractor(document);
            fileContent = extractor.getText();
            document.close();
        }
        return fileContent;
    }
}



